package com.blank.javawebexam.controler;

import com.alibaba.fastjson.JSONObject;
import com.blank.javawebexam.pojo.Student;
import com.blank.javawebexam.service.Impl.StudentServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/StudentInfoServlet")
public class StudentInfoServlet extends HttpServlet {
    private  static  ApplicationContext ctx;
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    this.doGet(request,response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

         ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        StudentServiceImpl studentServiceImpl = (StudentServiceImpl) ctx.getBean("studentService");
        String option = request.getParameter("op");
        switch (option){
            case "listStudent":
            default:
                response.setContentType("text/html;charset=utf-8");
                List<Student> list = studentServiceImpl.getList();
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("code", 0);
                map.put("msg", "success");
                map.put("count",list.size());
                map.put("data", list);
                String result = JSONObject.toJSONString(map);
                response.getWriter().write(result);
                break;
            case "delStudent":
                int id = Integer.parseInt(request.getParameter("id"));
                studentServiceImpl.delStudentById(id);
                break;
        }


    }




}
